package br.com.rookgraph.run;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import br.com.rookgraph.Edge;
import br.com.rookgraph.Graph;

public class ReadFileGraph {

	private BufferedReader in;
	private int size = -1;
	private int order;
	
	public ReadFileGraph(String file) {
		this.in = prepareInput(file);
	}

	public Graph read() {
		Graph graph = null;
		try {
			String line = this.in.readLine();
			if(line != null && line.contains("@")){
				line = line.replace("@", "");
				order = Integer.valueOf(line);
			}
			if(line != null)
			graph = new Graph(order);
			
			line = this.in.readLine();

			
			while( line != null && !line.equals("")){
				
				
				String[] split = line.split(" "); 
				
				if(!split[0].contains("#")&& !split[0].equals("")){
					Edge edger = new Edge(Integer.valueOf(split[0]),Integer.valueOf(split[1]));
					graph.addEdge(edger);
				}
					
				line = this.in.readLine();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return graph;
	}
	
	/**
	 * Prepara a leitura  com base no args do programa.
	 * O primeiro args especifica o arquivo de entrada,
	 * se ele estiver null, adimite a entrada padrão.
     *
	 * @param args
	 * @return
	 */
	private BufferedReader prepareInput(String args) {
		try {

			Reader inputStreamReader = args == null ? new InputStreamReader(System.in) : new FileReader(new File(args));

			return new BufferedReader(inputStreamReader);

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		return null;

	}

	
}
